<template>
  <a-card :bordered="false" >
    <div class="table-page-search-wrapper" v-if="createFormBox">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="4" :sm="24" style="min-width: 230px;">
            <a-form-item>
              <a-input v-model="queryParam.experimentName" placeholder="请输入试验名称" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24" style="min-width: 230px;">
            <a-form-item>
              <a-select v-model="queryParam.status" placeholder="状态">
                <a-select-option value="0">全部</a-select-option>
                <a-select-option value="1">成功</a-select-option>
                <a-select-option value="2">失败</a-select-option>
                <a-select-option value="3">未发送</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24" style="min-width: 260px;">
            <a-form-item>
              <a-range-picker v-model="queryParam.dateRange"/>
            </a-form-item>
          </a-col>
          <div style="float: right;margin-right:24px;">
            <a-button type="primary" icon="plus" size="20" @click="createFormBox=false" v-if="operationPermission['add']">创建通知</a-button>
          </div>
        </a-row>
      </a-form>
      <s-table
        class="table_style"
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :alert="options.alert"
        :rowSelection="options.rowSelection"
        showPagination="auto">
        <span slot="serial" slot-scope="text,record,index">{{ index + 1 }}</span>
        <span slot="action" slot-scope="text,record,index" class="operation_button_box_notification">
          <template>
            <a-button v-if="'失败'===record.statusName && operationPermission['resend']" size="small" @click="handleResend(record)" class="operation_button_edit_notification">重发</a-button>
            <a-button v-if="operationPermission['delete']" size="small" class="operation_button_release_notification" @click="handleDelete(record)">删除</a-button>
          </template>
        </span>
      </s-table>
    </div>
    <notification-form v-else @ok="handleOk" @Cancel="CreateFormHandleCancel" />
    <!-- <test-design @ok="handleOk"  ref="modal" ></test-design>
    <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    <a-modal :footer="null" v-model="confirmDelete" @ok="handleOk">
      <template slot="title">
        <p class="createFormEdit_title">删除提醒</p>
      </template>

      <div class="createFormEdit_content" style="height: 40px;margin-top: -80px">
        <p class="createFormEdit_content">确认删除{{ selectedMessage.title }}吗？</p>

        <div class="createFormEdit_font_box" style="margin-top: -40px">
          <div class="createFormEdit_font" style="margin-right: -40px">
            <a-button size="large" key="cancel" @click="handleCancel" style="margin-left:20px;">取消</a-button>
            <a-button
              size="large"
              key="forward"
              :loading="confirmLoading"
              type="primary"
              @click="deleteMessage"
              style="margin-left:20px;">确定</a-button>

          </div>
        </div>

      </div>
    </a-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
// import TestDesign from './modules/TestDesign'
import NotificationForm from './modules/NotificationForm'
import { getMessageList, deleteMessage, postMessageResend } from '@/api/manage'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    NotificationForm
    // TestDesign
  },
  data () {
    return {
      operationPermission:{},
      createFormBox: true,
      confirmDelete: false,
      confirmLoading: false,
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      selectedMessage: '',
      visible: false,
      designArray: {
        '0': '预发布',
        '1': '进行中',
        '2': '暂停中',
        '3': '已结束'
      },
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          // dataIndex: 'id',
          align: 'center'
        },
        {
          title: '目标用户',
          dataIndex: 'sendGoal',
          align: 'center'
        },
        {
          title: '标题',
          dataIndex: 'title',
          align: 'center'
        },
        {
          title: '描述',
          dataIndex: 'content',
          // needTotal: true,
          // customRender: (text) => text + ' 次',
          align: 'center'
        },
        // {
        //   title: '项目负责人',
        //   dataIndex: 'status',
        //   align: 'center'
        // },
        // {
        //   title: '申办方',
        //   dataIndex: 'description',
        //   align: 'center'
        // },
        {
          title: '状态',
          dataIndex: 'statusName',
          // scopedSlots: { customRender: 'status' },
          align: 'center'
        },
        {
          title: '发送时间',
          // dataIndex: 'updatedAt',
          // align:'center'

          dataIndex: 'sendTime',
          key: 'sendTime',
          // slots: { title: 'customTitle' },
          // scopedSlots: { customRender: 'updatedAt' },
          // sorter: true,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '200px',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        let status = ''
        if (this.queryParam.status) {
          status = this.queryParam.status
        }

        if (status === '0') {
          status = ''
        }

        let experimentName = ''
        if (this.queryParam.experimentName) {
          experimentName = this.queryParam.experimentName
        }

        let startDate = ''
        let endDate = ''
        try {
          if (this.queryParam.dateRange) {
            startDate = this.queryParam.dateRange[0].format('YYYY-MM-DD')
            endDate = this.queryParam.dateRange[1].format('YYYY-MM-DD')
          }
        } catch (e) {
          console.log('loadData.param', e)
        }

        const param = {
          startDate: startDate,
          endDate: endDate,
          experimentName: experimentName,
          status: status
        }

        console.log('loadData.parameter', parameter)
        return getMessageList(Object.assign(parameter, param))
          .then(res => {
            console.log(res.data.message)
            res.data.data = res.data.list
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true
    }
  },
  filters: {
    statusFilter (type) {
      // return statusMap[type].text
    },
    statusTypeFilter (type) {
      // return statusMap[type].status
    }
  },
  created () {
    let list = JSON.parse(localStorage.getItem("operationPermission"))
    list.forEach(element => {
      if (element.permissionId == 'messageNotification') { 
        element.actionVOS.forEach(i => {
          this.operationPermission[i.action] = i.defaultCheck
        });
      }      
    });
    this.tableOption()
    // getRoleList({ t: new Date() })
  },
  methods: {
    onChangeitem (date, dateString) {
      console.log(date, dateString)
    },

    CreateFormHandleCancel () {
      this.createFormBox = true
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: record.no === 'No 2', // Column configuration not to be checked
                name: record.no
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleResend (record) {
      console.log(record)
      const body = {
        id: record.id
      }

      // console.log('loadData.parameter', parameter)
      postMessageResend(body)
        .then(res => {
          console.log(res.message)
          // res.data.data = res.data.list
          // return res.data
          if (res.code === 200) {
            this.$message.success(res.message)
            // this.createFormEdit = false
            this.$refs.table.refresh(true)
            // this.createFormSuccess = true
            // this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
      // this.$refs.modal.edit(record)
    },
    handleDelete (record) {
      this.confirmDelete = true
      this.selectedMessage = record
    },
    handleCancel () {
      this.confirmDelete = false
      this.confirmLoading = false
    },
    deleteMessage () {
      if (!this.selectedMessage || !this.selectedMessage.id) {
        return
      }

      const param = {
        id: this.selectedMessage.id
      }
      this.confirmLoading = true
      // console.log('loadData.parameter', parameter)
      deleteMessage(param)
        .then(res => {
          console.log(res.message)
          // res.data.data = res.data.list
          // return res.data
          this.confirmDelete = false
          this.confirmLoading = false
          if (res.code === 200) {
            this.$message.success(res.message)
            // this.createFormEdit = false
            this.$refs.table.refresh(true)
            // this.createFormSuccess = true
            // this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
      // if (record.status !== 0) {
      //   this.$message.info(`${record.no} 订阅成功`)
      // } else {
      //   this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      // }
    },
    handleOk () {
      this.createFormBox = true
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    tableStatusEvent (v) {
      // console.log(this.$refs.tableStatusEvent,"徐强ggg")
      // this.$refs.tableStatusEvent.onclick
      // this.visible = false
      console.log(this.visible, '徐强')
    },
    aaa () {

    }
  },
  watch: {
    queryParam: {
      handler (newValue, oldValue) {
        this.$refs.table.refresh(true)
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>

.table_status {
  margin: 5px;
}
.ant-popover-title {
  width: 98px;
  height: 22px;
  font-size: 14px;
  font-family: PingFangSC-Regular, Microsoft Yahei, sans-serif;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
}
.createFormEdit_title {
  font-size: 24px;
  font-family: PingFangSC-Medium, Microsoft Yahei, sans-serif;
  font-weight: 700;
  color: rgba(0, 0, 0, 0.85);
  line-height: 24px;
  margin: 0px;
}
.createFormEdit_content {
  font-size: 20px;
  width: 400px;
  margin: 80px 20px;
}
.createFormEdit_content_modal {
  margin: 22px 66px 50px 66px;
}

.createFormEdit_title_box {
  margin-top: -30px;
}
.createFormEdit_font_box {
  height: 50px;
  .createFormEdit_font {
    float: right;
  }
}
.ant-popover-inner-content {
  padding: 5px 10px;
}
.table_status_box:hover {
  background: red;
}
.popover_hint {
  background: red;
}
.operation_button_box_notification {
  padding: 0px;
}
.operation_button_details {
  width: 74px;
  height: 32px;
}
.operation_button_release_notification {
  width: 74px;
  height: 32px;
  margin-left: 10px;
  border: 0px #EE7272 solid;
  background: #EE7272;
  color: #fff;
}
.operation_button_release_notification span {
  color: #fff;
}
.operation_button_release_notification:hover {
  border: 1px #EE7272 solid!important;
  background: #EE7272;
  opacity: 0.8;
}
.operation_button_edit_notification {
  width: 74px;
  height: 32px;
  margin-left: 10px;
  background: #eea91c;
  color: #fff;
}
.operation_button_edit_notification span {
  color: #fff;
}
.operation_button_edit_notification:hover {
  border: 1px #eea91c solid!important;
  background: #eea91c;
  opacity: 0.8;
}
/*}*/
</style>
